package com.small.controller.common;

import com.small.common.Const;
import com.small.pojo.User;
import com.small.util.CookieUtil;
import com.small.util.JsonUtil;
import com.small.util.RedisShradedPoolUtil;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @create: xie
 * 重置用户session的时间
 */
public class SessionExpireFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest)request;
        //取得cookie
        String loginToken = CookieUtil.readLoginToken(httpServletRequest);
        if(StringUtils.isNoneEmpty(loginToken)){
            //不为空就获取用户信息
            String userJsonStr = RedisShradedPoolUtil.get(loginToken);
            User user = JsonUtil.string2Obj(userJsonStr, User.class);
            if(user!=null){
                //如果用户信息不为空，则刷新session时间，即调用expire
                RedisShradedPoolUtil.expire(loginToken, Const.RedisCacheExtime.REDIS_SESSION_EXTIME);
            }
        }
        chain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
